package com.xxc.hs.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import cn.com.newland.nle_sdk.responseEntity.SensorReaTimeData;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.CloudService;
import cn.com.newland.nle_sdk.util.CloudServiceListener;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xxc.hs.R;
import com.xxc.hs.bean.CloudInfo;
import com.xxc.hs.bean.MusicFilePathInfo;
import com.xxc.hs.bean.UserInfo;
import com.xxc.hs.funActivity.ChartActivity;
import com.xxc.hs.funActivity.DataActivity;
import com.xxc.hs.funActivity.PanelActivity;
import com.xxc.hs.funActivity.WaringActivity;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("ALL")
public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private TextView tv_time, tv_power, tv_status, tv_userType;                             //顶部系统配置
    private View view, waterTempCard, phCard, dissolvedCard, waterLevelCard;                   //水质卡片
    private View safe_sensor_card, feeding_sensor_card, oxygen_sensor_card, sun_sensor_card;                  //模块卡片
    private View panel_sensor_card, chart_sensor_card, data_sensor_card;                                 //快捷功能卡片
    private TextView waterTempValue, waterTempStatus, waterTempType, phValue, phStatus, phType, dissolvedValue, dissolvedStatus, dissolvedType, waterLevelValue, waterLevelStatus, waterLevelType;  //水质配置
    private TextView safe_system_name, safe_system_status, safe_system_desc, feeding_system_name, feeding_system_status, feeding_system_desc, oxygen_system_name, oxygen_system_status, oxygen_system_desc, sun_system_name, sun_system_status, sun_system_desc;  //模块状态配置// 模块配置
    private View safe_status_dot, feeding_status_dot, oxygen_status_dot, sun_status_dot;    //模块状态配置
    private TextView panel_function_text, chart_function_text, data_fuinction_text;         //快捷功能配置
    private TextView overview_status, overview_tip;         //养殖状态配置

    private CloudService cloudService;

    private Handler handler;
    private Runnable runnable;
    private SimpleDateFormat dateFormat;
    private BroadcastReceiver broadcastReceiver;
    private MediaPlayer mediaPlayer;
    private UserInfo userInfo = UserInfo.getUserInfo();

    // 线程控制标志
    private AtomicBoolean isRunning = new AtomicBoolean(false);
    private Thread dataThread;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_home, container, false);
        try {
            initView();
            if (userInfo != null)
                tv_userType.setText(userInfo.getUsername().equals("admin") ? "管理员" : userInfo.getUsername());
            if (CloudInfo.getCloudService() == null) {
                CloudInfo.setCloudService();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            if (CloudInfo.getCloudService() != null) {
                cloudService = CloudInfo.getCloudService();
            }
            startDataThread();      //启动线程获取数据
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 启动线程
     */
    private void startDataThread() {
        try {
            if (dataThread != null && dataThread.isAlive()) {
                Log.d(TAG, "Data thread already running");
                return;
            }

            isRunning.set(true);
            dataThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isRunning.get()) {
                        getData();
                        updateFeeding();
                        updateOxyen();
                        try {
                            Thread.sleep(1000 * 4);
                        } catch (InterruptedException e) {
                            // 线程被中断时退出循环
                            Log.d(TAG, "Data thread interrupted");
                            break;
                        }
                    }
                }
            });
            dataThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取数据
     */
    private void getData() {
        try {
            cloudService.getSensorsRealTimeData(CloudInfo.ProjectId, new CloudServiceListener<BaseResponseEntity<List<SensorReaTimeData>>>() {
                @Override
                protected void onResponse(BaseResponseEntity<List<SensorReaTimeData>> listBaseResponseEntity) {
                    if (listBaseResponseEntity.getStatus() != 0) {
                        Log.e(TAG, "云服务数据获取失败");
                        return;
                    }
                    for (SensorReaTimeData data : listBaseResponseEntity.getResultObj()) {
                        String apiTag = data.getApiTag();
                        String value = data.getValue();

                        parseData(apiTag, value);
                    }


                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 解析数据
     */
    private void parseData(String tag, String value) {
        try {
            if (tag.equals(CloudInfo.UHF))
                return;

            float values = 0;
            try {
                BigDecimal bd = new BigDecimal(value).setScale(3, RoundingMode.HALF_UP);
                values = bd.floatValue();
            } catch (Exception e) {
                e.printStackTrace();
            }

            switch (tag) {
                case CloudInfo.PH:
                    updatePH(values);
                    break;
                case CloudInfo.WATERTEMP:
                    updateWaterTemp(values);
                    break;
                case CloudInfo.DISSOLVED:
                    updateDissolved(values);
                    break;
                case CloudInfo.WATERLEVEL:
                    updateWaterLevel(values);
                    break;
                case CloudInfo.SUN:
                    updateSun(values);
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void updateFeeding() {
        try {
            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (WaterFragment.modelIsRunnig) {
                        feeding_status_dot.setBackgroundResource(R.drawable.dot_running);
                        feeding_system_status.setText("运行中");
                        feeding_system_desc.setText("运行");
                        feeding_system_status.setTextColor(Color.GREEN);
                    } else {
                        feeding_status_dot.setBackgroundResource(R.drawable.dot_standby);
                        feeding_system_status.setText("停止中");
                        feeding_system_desc.setText("停止");
                        feeding_system_status.setTextColor(Color.GRAY);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateOxyen() {
        try {
            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (WaterFragment.modelIsRunnig) {
                        oxygen_status_dot.setBackgroundResource(R.drawable.dot_running);
                        oxygen_system_status.setTextColor(Color.GREEN);
                        oxygen_system_status.setText("运行中");
                        oxygen_system_desc.setText("运行");
                    } else {
                        oxygen_status_dot.setBackgroundResource(R.drawable.dot_standby);
                        oxygen_system_status.setTextColor(Color.GRAY);
                        oxygen_system_status.setText("停止中");
                        oxygen_system_desc.setText("停止");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateWaterLevel(float value) {
        try {
            waterLevelValue.post(new Runnable() {
                @Override
                public void run() {
                    waterLevelValue.setText(value + "");
                    if (value > 40) {
                        waterLevelStatus.setBackgroundResource(R.drawable.bg_status_waring);
                        waterLevelStatus.setText("过高");
                        startAudio(MusicFilePathInfo.WaterLevelHighFilePath);
                    } else if (value < 15) {
                        waterLevelStatus.setBackgroundResource(R.drawable.bg_status_danger);
                        waterLevelStatus.setText("过低");
                        startAudio(MusicFilePathInfo.WaterLevelLowFilePath);
                    } else {
                        waterLevelStatus.setBackgroundResource(R.drawable.bg_status_normal);
                        waterLevelStatus.setText("正常");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateDissolved(float value) {
        try {
            dissolvedValue.post(new Runnable() {
                @Override
                public void run() {
                    dissolvedValue.setText(value + "");
                    if (value < 5) {
                        //打开增氧机 - 播放语音播报
                        dissolvedStatus.setBackgroundResource(R.drawable.bg_status_danger);
                        dissolvedStatus.setText("过低");
                        startAudio(MusicFilePathInfo.DissolvedLowFilePath);
                    } else {
                        dissolvedStatus.setBackgroundResource(R.drawable.bg_status_normal);
                        dissolvedStatus.setText("正常");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateWaterTemp(float value) {
        try {
            waterTempValue.post(new Runnable() {
                @Override
                public void run() {
                    waterTempValue.setText(value + "");
                    if (value < 15) {
                        //打开加热棒，减少换水 - 播放语音播报
                        waterTempStatus.setBackgroundResource(R.drawable.bg_status_waring);
                        waterTempStatus.setText("过低");
                        startAudio(MusicFilePathInfo.WaterTempLowFilePath);
                    } else if (value > 30) {
                        //打开增氧机
                        waterTempStatus.setBackgroundResource(R.drawable.bg_status_danger);
                        waterTempStatus.setText("过高");
                        startAudio(MusicFilePathInfo.WaterTempHighFilePath);
                    } else {
                        waterTempStatus.setBackgroundResource(R.drawable.bg_status_normal);
                        waterTempStatus.setText("正常");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateSun(float value) {
        try {
            sun_system_desc.post(new Runnable() {
                @Override
                public void run() {
                    sun_system_desc.setText(value + " V");
                    if (value < 5){
                        sun_status_dot.setBackgroundResource(R.drawable.dot_error);
                        sun_system_status.setText("电量不足");
                        sun_system_status.setTextColor(Color.RED);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePH(float value) {
        try {
            phValue.post(new Runnable() {
                @Override
                public void run() {
                    phValue.setText(value + "");
                    if (value < 6.0) {
                        //泼洒生石灰 - 播放语音播报
                        phStatus.setBackgroundResource(R.drawable.bg_status_waring);
                        phStatus.setText("过低");
                        startAudio(MusicFilePathInfo.PhLowFilePath);
                    } else if (value > 8.0) {
                        //换水，泼洒柠檬酸
                        phStatus.setBackgroundResource(R.drawable.bg_status_danger);
                        phStatus.setText("过高");
                        startAudio(MusicFilePathInfo.PhHighFilePath);
                    } else {
                        phStatus.setBackgroundResource(R.drawable.bg_status_normal);
                        phStatus.setText("正常");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化配置
     */
    private void initView() {
        try {
            //顶部系统状态初始化
            tv_time = view.findViewById(R.id.tv_time);
            tv_power = view.findViewById(R.id.tv_power);
            tv_status = view.findViewById(R.id.tv_status);
            tv_userType = view.findViewById(R.id.tv_userType);

            //水温卡片
            waterTempCard = view.findViewById(R.id.waterTemp_sensor_card);
            waterTempValue = waterTempCard.findViewById(R.id.sensor_value);
            waterTempStatus = waterTempCard.findViewById(R.id.sensor_status);
            waterTempType = waterTempCard.findViewById(R.id.sensor_type);
            waterTempType.setText("水温");

            //PH卡片
            phCard = view.findViewById(R.id.ph_sensor_card);
            phValue = phCard.findViewById(R.id.sensor_value);
            phStatus = phCard.findViewById(R.id.sensor_status);
            phType = phCard.findViewById(R.id.sensor_type);
            phType.setText("PH");

            //溶氧量卡片
            dissolvedCard = view.findViewById(R.id.dissolved_sensor_card);
            dissolvedValue = dissolvedCard.findViewById(R.id.sensor_value);
            dissolvedStatus = dissolvedCard.findViewById(R.id.sensor_status);
            dissolvedType = dissolvedCard.findViewById(R.id.sensor_type);
            dissolvedType.setText("溶解氧");

            //水位卡片
            waterLevelCard = view.findViewById(R.id.waterLevel_sensor_card);
            waterLevelValue = waterLevelCard.findViewById(R.id.sensor_value);
            waterLevelStatus = waterLevelCard.findViewById(R.id.sensor_status);
            waterLevelType = waterLevelCard.findViewById(R.id.sensor_type);
            waterLevelType.setText("水位");

            //智能安防模块
            safe_sensor_card = view.findViewById(R.id.safe_sensor_card);
            safe_system_name = safe_sensor_card.findViewById(R.id.system_name);
            safe_system_status = safe_sensor_card.findViewById(R.id.system_status);
            safe_system_desc = safe_sensor_card.findViewById(R.id.system_desc);
            safe_status_dot = safe_sensor_card.findViewById(R.id.status_dot);
            safe_system_name.setText("智能安防模块");
            safe_system_status.setText("运行中");
            safe_system_desc.setText("实时监控中");

            //智能投喂系统模块
            feeding_sensor_card = view.findViewById(R.id.feeding_sensor_card);
            feeding_system_name = feeding_sensor_card.findViewById(R.id.system_name);
            feeding_system_status = feeding_sensor_card.findViewById(R.id.system_status);
            feeding_system_desc = feeding_sensor_card.findViewById(R.id.system_desc);
            feeding_status_dot = feeding_sensor_card.findViewById(R.id.status_dot);
            feeding_status_dot.setBackgroundResource(R.drawable.dot_standby);
            feeding_system_name.setText("智能投喂系统模块");
            feeding_system_status.setText("停止中");
            feeding_system_status.setTextColor(Color.GRAY);
            feeding_system_desc.setText("停止");

            //智能供氧控制系统模块
            oxygen_sensor_card = view.findViewById(R.id.oxygen_sensor_card);
            oxygen_system_name = oxygen_sensor_card.findViewById(R.id.system_name);
            oxygen_system_status = oxygen_sensor_card.findViewById(R.id.system_status);
            oxygen_system_desc = oxygen_sensor_card.findViewById(R.id.system_desc);
            oxygen_status_dot = oxygen_sensor_card.findViewById(R.id.status_dot);
            oxygen_status_dot.setBackgroundResource(R.drawable.dot_standby);
            oxygen_system_name.setText("智能供氧控制系统模块");
            oxygen_system_status.setText("停止中");
            oxygen_system_status.setTextColor(Color.GRAY);
            oxygen_system_desc.setText("停止");

            //光伏能源监控模块
            sun_sensor_card = view.findViewById(R.id.sun_sensor_card);
            sun_system_name = sun_sensor_card.findViewById(R.id.system_name);
            sun_system_status = sun_sensor_card.findViewById(R.id.system_status);
            sun_system_desc = sun_sensor_card.findViewById(R.id.system_desc);
            sun_status_dot = sun_sensor_card.findViewById(R.id.status_dot);
            oxygen_status_dot.setBackgroundResource(R.drawable.dot_running);
            sun_system_name.setText("光伏能源监测系统模块");
            sun_system_status.setText("运行中");
            sun_system_status.setTextColor(Color.GREEN);
            sun_system_desc.setText("0.00v");

            //专家功能
            panel_sensor_card = view.findViewById(R.id.panel_sensor_card);
            panel_function_text = panel_sensor_card.findViewById(R.id.function_text);
            panel_function_text.setText("专家问诊");
            panel_sensor_card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(requireActivity(), PanelActivity.class));
                }
            });

            //AI功能
            chart_sensor_card = view.findViewById(R.id.chart_sensor_card);
            chart_function_text = chart_sensor_card.findViewById(R.id.function_text);
            chart_function_text.setText("AI问答");
            chart_sensor_card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(requireActivity(), ChartActivity.class));
                }
            });

            //历史数据查询功能
            data_sensor_card = view.findViewById(R.id.data_sensor_card);
            data_fuinction_text = data_sensor_card.findViewById(R.id.function_text);
            data_fuinction_text.setText("历史数据");
            data_sensor_card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(requireActivity(), DataActivity.class));
                }
            });


            //养殖状态配置
            overview_status = view.findViewById(R.id.overview_status);
            overview_tip = view.findViewById(R.id.overview_tip);

            handler = new Handler(Looper.getMainLooper());
            dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void startAudio(String filePath) {
        try {
            // 重置MediaPlayer
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();

            // 设置assets中的音频数据源
            mediaPlayer.setDataSource(requireActivity().getAssets().openFd(filePath));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopAudio() {
        try {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                try {
                    // 重置MediaPlayer以便重新播放
                    mediaPlayer.reset();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    private void updateBatteryStatus(Intent intent) {
        try {
            //获取电量百分比
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryPercent = (level / (float) scale) * 100;
            tv_power.setText("电量：" + String.format("%.1f%%", batteryPercent));

            // 获取充电状态
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            String statusText;
            switch (status) {
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    statusText = "充电中";
                    // 获取充电方式
                    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                    if (chargePlug == BatteryManager.BATTERY_PLUGGED_USB) {
                        statusText += "（USB）";
                    } else if (chargePlug == BatteryManager.BATTERY_PLUGGED_AC) {
                        statusText += "（电源）";
                    } else if (chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
                        statusText += "（无线）";
                    }
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    statusText = "放电中";
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    statusText = "已充满";
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    statusText = "未充电";
                    break;
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                default:
                    statusText = "未知状态";
                    break;
            }
            tv_status.setText("状态：" + statusText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startTimer() {
        try {
            if (runnable != null) {
                Log.d(TAG, "Timer already started");
                return;
            }

            runnable = new Runnable() {
                @Override
                public void run() {
                    tv_time.setText(dateFormat.format(new Date()));
                    if (handler != null) {
                        handler.postDelayed(runnable, 1000);
                    }
                }
            };
            if (handler != null) {
                handler.post(runnable);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopTimer() {
        try {
            if (handler != null && runnable != null) {
                handler.removeCallbacks(runnable);
                runnable = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放MediaPlayer资源
     */
    private void releaseMediaPlayer() {
        try {
            if (mediaPlayer != null) {
                stopAudio();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        try {
            startTimer();
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryStatus(intent);
                }
            };
            IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            if (requireContext() != null) {
                requireContext().registerReceiver(broadcastReceiver, filter);
            }
            isRunning.set(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            stopTimer();
            stopAudio();

            if (broadcastReceiver != null && requireContext() != null) {
                requireContext().unregisterReceiver(broadcastReceiver);
                broadcastReceiver = null;
            }
            isRunning.set(false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            // 停止数据线程
            isRunning.set(false);
            if (dataThread != null) {
                dataThread.interrupt();
                dataThread = null;
            }

            cloudService = null;

            stopTimer();

            // 释放MediaPlayer资源
            releaseMediaPlayer();

            if (broadcastReceiver != null && requireContext() != null) {
                requireContext().unregisterReceiver(broadcastReceiver);
                broadcastReceiver = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}